<div class="page">
	<div class="menu">
		<?php include('modules/members/dashboard.php');?>
    </div>
	<div class="products-list" style="overflow:hidden;">
    <?php if($_GET['pedit']==true){ ?>
    <?php
        if($_SESSION['user'] != "admin" && $_SESSION['user'] != "superadmin"){
            echo '<h2 align="center" style="color:red; margin-top: 10%;">คุณไม่ใช่ผู้ดูแลระบบ ไม่มีสิทธิ์ในการแก้ไขสินค้า.</h2>';
			print_r($_SESSION);
            die();
        }
    ?>
    <input type="hidden" id="code" value="<?php echo $_GET['code'];?>" />
    <form action="#" method="POST" id="edit_products_form">
    <?php
        $get = 'SELECT
					`units`.`name` AS unit
					, `products`.*
				FROM
					`hkpacth_store`.`units`
				INNER JOIN `hkpacth_store`.`products` 
					ON (`units`.`id` = `products`.`unit_id`)
				WHERE code="'.$_GET['code'].'"';
        $getq= mysql_query($get)or die(mysql_error());
        $getm= mysql_fetch_assoc($getq);
    ?>
        <table width="600" border="0" cellpadding="10" id="edit_products">
            <tbody>
                <tr>
                    <td width="200" align="right"><img src="css/images/shoping_basket.png" width="110" title="เพิ่มพนักงาน" /></td>
                    <td align="left"><h2>แก้ไขสินค้า</h2></td>
                </tr>
                <tr>
                    <td align="right">ชื่อสินค้า</td>
                    <td align="left"><input type="text" name="name" id="name" value="<?php echo $getm['name'];?>"/></td>
                </tr>
                <tr>
                    <td align="right">ราคาต้นทุน</td>
                    <td align="left"><input type="text" name="cost" id="cost" value="<?php echo $getm['cost'];?>"/></td>
                </tr>
                <tr>
                    <td align="right">ราคา</td>
                    <td align="left"><input type="text" name="price" id="price" value="<?php echo $getm['price'];?>"/></td>
                </tr>
                <tr>
                    <td align="right">หน่วย</td>
                    <td align="left">
                    	<select name="unit_id" id="unit_id">
                    <?php 
						$uq = mysql_query('SELECT * FROM units'); 
						while($qrs= mysql_fetch_assoc($uq)){
					?>
                        <option value="<?php echo $qrs['id']; ?>" <?php ($getm['unit']==$qrs['name'])? print 'selected="selected"':'';?>><?php echo $qrs['name'];?></option>
                   	<?php }?>
                        </select>
                  	</td>
                </tr>
                <tr>
                    <td align="right">จำนวน </td>
                    <td><input type="text" name="num" id="num" value="<?php echo $getm['num'];?>"/></td>
                </tr>
                <tr>
                    <td align="right">ขนาดสติ๊กเกอร์ </td>
                    <td><input type="text" name="width" id="width" value="<?php echo $getm['width'];?>" style="width:70px;"/>&nbsp;X &nbsp; <input type="text" name="height" id="height" value="<?php echo $getm['height'];?>" style="width:70px;"/> (ยาว x สูง)</td>
                </tr>
                <tr>
                    <td align="right" valign="top">รูปภาพ </td>
                    <td align="left">
                    
                    <p id="button">
                        <a href="" class="btn" style="font-size:18px;cusor:pointer;" id="upload"><span>เลือกรูปภาพ</span></a>
                        <span id="status" ></span>
                    </p>   	    
                  	<div class="clear"></div>
                    <ul id="files">
                    <?php
                        $pic_num = isset($_SESSION['img'])? count($_SESSION['img']):0;
                        if($pic_num != 0){
						   echo '<input type="hidden" name="image_path" id="image_path" value="'.$_SESSION['img'].'"/>';               
                           echo '<li><img src="stickers/'.$_SESSION['img'].'" width="220" /></li>';
                        }elseif($getm['image_path'] != ""){
							echo '<input type="hidden" name="image_path" id="image_path" value="'.$getm['image_path'].'"/>';               
							echo '<img src="stickers/'.$getm['image_path'].'" width="200"  />';
						}else{
							echo '<img src="stickers/nopicture.gif" width="200"  />';
						}
                    ?>
                    </ul>
                   	</td>
                </tr>
                <tr>
                    <td align="right" valign="top">รายละเอียด </td>
                    <td align="left">
                    	<textarea name="detail" id="detail" cols="50" rows="5">
							<?php echo $getm['detail'];?>
                        </textarea>
                </tr>
                <tr>
                    <td align="right" valign="top">หมายเหตุ </td>
                    <td align="left"><textarea name="annotation" id="annotation" cols="50" rows="5"/><?php echo $getm['annotation'];?></textarea></td>
                </tr>
                <tr>
                    <td align="right"></td>
                    <td align="left">
                        <p style="margin-left:0px;margin-top:25px;" id="button">
                        	<a href="#" class="btn" style="font-size:25px;" id="update_products_btn" onClick="return false;">
                        	    <span>อัพเดท</span>
                            </a>
                            <span class="loading"></span>
                       	</p>
       	            </td>
                </tr>
            </tbody>
        </table>
    </form>
    <?php
	}else{
	?>
    	<p style="float:right;" id="button">
        	<a href="#" class="btn" style="font-size:25px;" id="delete_now"><span>ลบที่เลือก</span></a>
       	</p>
	    <p style="float:right;" id="button">
        	<a href="#" class="btn" style="font-size:25px;" id="order_now"><span>สั่งซื้อ</span></a>
       	</p>
    	<table id="products_list" width="100%">
        	<thead>
              <tr>
              	<th width="40">
                <input type="checkbox" onclick="$('input[name*=\'selected\']').attr('checked', this.checked);">
               	</th>
                <th width="40">ID</th>
            	<th>รายการสินค้า</th>
                <th width="50">ราคา</th>
                <th>หน่วย</th>
                <th width="60">เหลือ</th>
                <th>รายการโปรโมชัน</th>
                <th>หมายเหตุ</th>
              </tr>
            </thead>
            <tbody>
            <?php
            $sql = 'SELECT
                        `products`.*
                        , `units`.`name` AS unit
                    FROM
                        `hkpacth_store`.`units`
                        INNER JOIN `hkpacth_store`.`products`
                            ON (`units`.`id` = `products`.`unit_id`)';
			$q = mysql_query($sql)or die(mysql_error());
			while($rs = mysql_fetch_assoc($q)){?>
              <tr>
              	<td align="center"><input type="checkbox" name="selected[]" value="<?php echo $rs['code'];?>" /></td>
                <td align="center"><?php echo $rs['id'];?></td>
                <!--<td><a href="?m=products&p=order_products&pedit=true&code=<?php echo $rs['code'];?>"><?php echo $rs['code'];?></a></td>-->
            	<td>
                	<a href="?m=products&p=order_products&pedit=true&code=<?php echo $rs['code'];?>" class="vtip" title="<?php echo ($rs['detail']=="")?"ยังไม่มีรายละเอียด":$rs['detail'];?>">
						<?php echo $rs['name'];?>
                    </a>
               	</td>
                <td><span id="<?php echo $rs['id'];?>" field="price" class="dblclick"><?php echo number_format($rs['price'],2,'.',',');?></span></td>
                <td><?php echo $rs['unit'];?></td>
                <td><span id="<?php echo $rs['id'];?>" field="num" class="dblclick"><?php echo $rs['num'];?></span></td>
                <td><span id="<?php echo $rs['id'];?>" field="promotion" class="dblclick"><?php echo $rs['promotion'];?></span></td>
                <td><span id="<?php echo $rs['id'];?>" field="annotation" class="dblclick"><?php echo $rs['annotation'];?></span></td>
              </tr>
           	<?php } ?>
            </tbody>
        </table>
	<?php }?>
    </div>
</div>
<script type="text/javascript">
$(function(){
	$('#products_list tbody tr td input:checkbox').click( function() {
		if ( $(this).closest('tr').hasClass('row_selected') )
			$(this).closest('tr').removeClass('row_selected');
		else
			$(this).closest('tr').addClass('row_selected');
	} );
	
	var oTable = $('#products_list').dataTable({
		"bJQueryUI": true,
		"sPaginationType": "full_numbers",
		"sDom": '<"H"Tfrl>t<"F"ip>',
		"iDisplayLength": 40,
		"oTableTools": {
			"sSwfPath": "media/swf/copy_cvs_xls_pdf.swf",
			"aButtons": [ "xls"	]
		}
	});
	$(".dblclick").editable("query.php?editable=true&table=products", {
        indicator : "<img src='css/images/indicator.gif'>",
        id      : "elementid",
        name    : "newvalue",
        tooltip : "Doubleclick เพื่อแก้ไข",
		placeholder: '&nbsp;',
        event : "dblclick",
        style : "inherit",
		submit: 'OK',
		submitdata : function(value, setting){
			return {field:$(this).attr('field')}
		}
    });
	
    $('#order_now').click(function(){
		var selected = fnGetSelected(oTable);
        var products = "";
        var i = 0;
		
        $(selected).each(function(){
			
            if($(this).val() != "on"){
                products += "&products["+i+"][code]="+ $(this,'td').find('input:checkbox').val();
                products += "&products["+i+"][price]="+ $(this).find('td:eq(3)').text();
                products += "&products["+i+"][unit]="+$(this).find('td:eq(4)').text();
            }
            i++;
        });
		if(products != ""){	
		   $.ajax({
				type    : 'GET',
				url     : 'query.php',
				data    : 'order=true'+products,
				dataType: 'html',
				beforeSend : function(){$('.loading').html('<img src="css/images/loading.gif" alt="loading" >');},
				success : function(msg){
					if(msg.length > 10){
						//alert(msg);
						location.href = '?m=products&p=bill&bid='+msg;
					}else{
						alert(msg);
					}
				}
			});
		}else{
			alert('ท่านยังไม่มีรายการสินค้าที่เลือก');
		}
        return false;
    });
	
	$('#delete_now').click(function(){
		var selected = "";
		var i = 0;
		$('#products_list tbody tr td').find('input[type=checkbox]:checked').each(function(){
			if($(this).val() != "on"){
				selected += "&selected["+i+"]="+$(this).val();
			}
			i++;
		});
		if(selected != ""){
			if(confirm('คุณมั่นใจหรือไม่ที่ต้องการลบข้อมูล')){
				$.ajax({
					type 	: 'GET',
					url		: 'query.php',
					data	: "delete_selected=true&table=products"+selected,
					dataType: 'text',
					success	: function(msg){
						alert('ลบข้อมูลเรียบร้อยแล้ว');
						location.reload();
					}
				});
			}
		}else{
			alert('ท่านยังไม่มีรายการสินค้าที่เลือก');
		}

		return false;
	});

<?php
	if($_GET['m'] == "stickers" || $_GET['pedit'] == true){
?>
	$('#detail').wysiwyg();
	var count_img = 0;
	var btnUpload=$('#upload');
	var status=$('#status');
	new AjaxUpload(btnUpload, {
		action: 'upload-file.php',
		name: 'uploadfile',
		onSubmit: function(file, ext){
			if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
				// extension is not allowed 
				status.text('ไฟล์ที่คุณสามารถอัพโหลดได้คือ .jpg, .jpeg, .png และ .gif เท่านั้น');
				return false;
			}else if(count_img > 1){
				alert('คุณสามารถอัพโหลดรูปภาพได้สูงสุด 6 ภาพ');
				return false;
			}else{
				//alert(count_img);
			}
			status.text('Uploading...');
		},
		onComplete: function(file, response){
			//On completion clear the status
			status.text('');
			//Add uploaded file to list
			var imgstatus = response.split(',');
			
			if(imgstatus[0]==="success"){
				$('#files').html('');
				$('<li style="float:left;list-style:none;"></li>').appendTo('#files').html('<img src="stickers/'+imgstatus[1]+'" width="220" /><input type="hidden" name="image_path" id="image_path" value="'+imgstatus[1]+'"/>').addClass('success');
				count_img++;
				
			} else{
				$('<li style="float:left;list-style:none;"></li>').appendTo('#files').text(imgstatus[1]).addClass('error');
			}
	
		}
	});
	
<?php } ?>	
	$('#update_products_btn').click(function(){
		$.ajax({
			type 	: 'POST',
			url		: 'query.php',
			data	: {update_product:true, code:$('#code').val(), data:$(this).closest('form').serializeArray()},
			dataType: 'html',
			success	: function(msg){
				if(msg.trim() == ''){
					alert('แก้ไขข้อมูลสำเร้จแล้ว');
				}else{
					alert(msg);
				}
			}	
		});
		return false;
	});
	
});

function fnGetSelected( oTableLocal ){
	var aReturn = new Array();
	var aTrs = oTableLocal.fnGetNodes();
	
	for ( var i=0 ; i<aTrs.length ; i++ )
	{			
		if ( $(aTrs[i]).hasClass('row_selected') )
		{
			aReturn.push( aTrs[i] );
		}
	}
	return aReturn;
}
</script>
<style type="text/css">
.ui-state-default .ui-icon {
	float:right;
}
#edit_products {
	margin: 0px auto;
}
#files li {
	list-style:none;
}
</style>

